package com.wfx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jwt.util.JwtUtils;
import com.jwt.util.RsaUtils;
import com.wfx.entity.*;
import com.wfx.mapper.UserInfoMapper;
import com.wfx.mapper.WxbCustomerMapper;
import com.wfx.mapper.WxbMemeberMapper;
import com.wfx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxbMemeberMapper wxbMemeberMapper;
    @Autowired
    private WxbCustomerMapper wxbCustomerMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result login(UserDto userDto) {
        if (userDto == null) {
            return new Result(false,"参数不合法");
        }
        if("1".equals(userDto.getUserType())){
            QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("account",userDto.getUsername());
            UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
            if (userInfo == null) {
                return new Result(false,"用户名不存在");
            }
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(userDto.getPassword(), userInfo.getPassword());
            if (matches==false){
                return new Result(false,"用户名或密码错误");
            }
            //查询用户module信息
            UserInfo userInfo2 = userInfoMapper.findRoleByUser(userInfo);
            List<SysRole> userSysRole = userInfo2.getUserSysRole();
            UserInfo userInfo1 = userInfoMapper.findModulesByUser(userInfo);
            List<SysModule> modules = userInfo1.getUserModules();
            //查询用户role信息
            String moduleStr = "";
            String roleStr = "";
            for (SysModule module : modules) {
                moduleStr = moduleStr +","+module.getModuleName();
            }
            for (SysRole sysRole : userSysRole) {
                roleStr = sysRole.getRoleName()+","+roleStr;
            }
            //获取用户的角色和权限信息
            String joinStr = roleStr+moduleStr;
            userInfo.setRoleAndAuth(joinStr);
            //颁发令牌
            String token = genJwtToken(userInfo);
            if (token==null){
                return new Result(false,"用户名或密码错误");
            }
            return new Result(true,"登录成功",token);
        }

        if("2".equals(userDto.getUserType())){
            QueryWrapper<WxbMemeber> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("account",userDto.getUsername());
            WxbMemeber wxbMemeber = wxbMemeberMapper.selectOne(queryWrapper);
            if (wxbMemeber == null) {
                return new Result(false,"用户名不存在");
            }
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(userDto.getPassword(), wxbMemeber.getPassword());
            if (matches==false){
                return new Result(false,"用户名或密码错误");
            }
            String token = genJwtToken(wxbMemeber);
            if (token==null){
                return new Result(false,"用户名或密码错误");
            }
            return new Result(true,"登录成功",token);
        }
        if("3".equals(userDto.getUserType())){
            QueryWrapper<WxbCustomer> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("login_name",userDto.getUsername());
            WxbCustomer wxbCustomer = wxbCustomerMapper.selectOne(queryWrapper);
            if (wxbCustomer == null) {
                return new Result(false,"用户名不存在");
            }
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(userDto.getPassword(), wxbCustomer.getLoginPwd());
            if (matches==false){
                return new Result(false,"用户名或密码错误");
            }
            String token = genJwtToken(wxbCustomer);
            if (token==null){
                return new Result(false,"用户名或密码错误");
            }
            return new Result(true,"登录成功",token);
        }
        return new Result(false,"用户名或密码错误");
    }
    //验证码登录
    @Override
    public Result loginCode(UserDto userDto) {
        QueryWrapper<WxbMemeber> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",userDto.getUsername());
        WxbMemeber wxbMemeber = wxbMemeberMapper.selectOne(queryWrapper);
        if (wxbMemeber == null) {
            return new Result(false,"手机号不存在");
        }
        String key = userDto.getUsername();
        String redisCode = stringRedisTemplate.boundValueOps(key).get();
        if (redisCode==null){
            return new Result(false,"验证码失效");
        }
        if (!redisCode.equals(userDto.getPassword())){
            return new Result(false,"验证码错误");
        }
        String token = genJwtToken(wxbMemeber);
        if (token == null) {
            return new Result(false,"信息错误");
        }
        return new Result(true,"登录成功",token);
    }






    private String genJwtToken(Object user){
        try {
            //从类路径中获取私钥
            String privateKeyPath = ResourceUtils.getFile("classpath:ras_private").getPath();
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);

            String jwtToken = JwtUtils.generateTokenExpireInMinutes(user, privateKey, 30);
            System.out.println(jwtToken);
            return jwtToken;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
